//
//  SearchStrDBTools.m
//  NC-Trendy
//
//  Created by LeungChaos on 16/2/26.
//  Copyright © 2016年 liang. All rights reserved.
//

#import "SearchStrDBTools.h"

@implementation SearchStrDBTools

+ (NSManagedObjectContext *)objContext {
    return [AppDelegate shareAppDelegate].managedObjectContext;
}

+ (NSFetchRequest *)fetchRequest {
    return [NSFetchRequest fetchRequestWithEntityName:@"CoreSearchStr"];
}

+ (NSEntityDescription *)entityDesc {
    return [NSEntityDescription entityForName:@"CoreSearchStr" inManagedObjectContext:[self objContext]];
}

+ (void)insertSearchStr:(NSString *)str errorInfo:(void(^)(NSError *error))errorBlock {
    NSError *error;
    NSFetchRequest *fetchRequest = [self fetchRequest];
    fetchRequest.predicate = [NSPredicate predicateWithFormat:@"search_str = %@",str];
    NSArray *array = [[self objContext]executeFetchRequest:fetchRequest error:&error];
    if (array.count == 0) {
        NSTimeInterval now = [[NSDate date]timeIntervalSinceReferenceDate];
        CoreSearchStr *cStr = [[CoreSearchStr alloc]initWithEntity:[self entityDesc] insertIntoManagedObjectContext:[self objContext]];
        cStr.search_id = [NSString stringWithFormat:@"%d",(int)now];
        cStr.search_str = str;
        [[self objContext]insertObject:cStr];
        [[self objContext]save:&error];
    }
    if (errorBlock) {
        errorBlock(error);
    }
}

+ (NSMutableArray<NSString *> *)searchStrArrayWithErrorInfo:(void(^)(NSError *error))errorBlock {
    NSError *error;
    NSFetchRequest *fetchRequest = [self fetchRequest];
    NSMutableArray *resultArray = [NSMutableArray arrayWithArray:[[self objContext]executeFetchRequest:fetchRequest error:&error]];
    if (errorBlock) {
        errorBlock(error);
    }
    if (resultArray.count > 0) {
        [resultArray sortUsingComparator:^NSComparisonResult(CoreSearchStr *_Nonnull obj1, CoreSearchStr *_Nonnull obj2) {
            if ([obj2.search_id integerValue] > [obj1.search_id integerValue]) {
                return YES;
            } else {
                return NO;
            }
        }];
        NSMutableArray *mutArray = [NSMutableArray array];
        [resultArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            CoreSearchStr *cstr = obj;
            [mutArray addObject:cstr.search_str];
        }];
        return mutArray;
    } else {
        return nil;
    }
}

+ (void)deleteAllSearchStrWithErrorInfo:(void(^)(NSError *error))errorBlock {
   __block NSError *error;
    NSArray *array = [[self objContext]executeFetchRequest:[self fetchRequest] error:&error];
    if (array.count > 0) {
        [array enumerateObjectsUsingBlock:^(CoreSearchStr *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [[self objContext]deleteObject:obj];
            [[self objContext] save:&error];
        }];
    }
    if (errorBlock) {
        errorBlock(error);
    }
}

@end


